package scau.mis4.chanyulin.web.login;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import scau.mis4.chanyulin.base.common.BaseController;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by cyl on 2017/2/26.
 * 登录接口
 */
@RestController
@RequestMapping("/log")
public class LoginController extends BaseController {
    @GetMapping("/index")
    public String showLogin() {
        return "/login";
    }

    @PostMapping(value = "/login", produces = "application/json")
    public String checkLogin(String username, String password) throws IOException {
        logger.entry(username, password);
        logger.info("======进入登陆======");
        String msg = doLogin(username,password);
        // ServletContext context = request.getServletContext();
        Model model = new ExtendedModelMap();
        if (msg.equals("登录成功")) {
            model.addAttribute("result", "登陆成功");
            return createSuccessJSON(model);
        } else if (msg.equals("账号不存在")){
            // context.setAttribute("error","账号不存在");
            model.addAttribute("result", "账号不存在");
            return createErrorJSON(model);
        } else if (msg.equals("账号或密码错误")){
            // context.setAttribute("error","账号或密码错误");
            model.addAttribute("result", "账号或密码错误");
            return createErrorJSON(model);
        } else{
            // context.setAttribute("error","登录异常,暂时无法登录");
            model.addAttribute("result", "登录异常,暂时无法登录");
            return createErrorJSON(model);
        }
    }

    @PostMapping(value = "/logout",produces = "application/json")
    @ResponseBody
    public String logout() {
        Subject subject=SecurityUtils.getSubject();
        subject.logout();
        return createSuccessJSON("注销成功");
    }

    @GetMapping(value = "/check_login",produces = "application/json")
    @ResponseBody
    public String checkLogin(){
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        if (username == null) {
            return "0";
        } else
            return "1";
    }

    @GetMapping(value = "/check_superadmin",produces = "application/json")
    @ResponseBody
    public String getCurrentAuthLevel() {
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        if (username == null) return "0";
        boolean check = subject.hasRole("0");
        if (!check)
            return "0";
        else
            return "1";
    }

}
